#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#include "semaphore.h"

/*
 * REMINDER:
 * seat linked list is protected by pthread mutex
 * pthread_cond is used with the worker queue
 * semaphore is used as mutex for the standby list
 */

void sem_init(m_sem_t *s, int value) {
    pthread_mutex_init(&(s->mutex), NULL); // assume s to be created dynamically, remember to free!!
    pthread_cond_init(&(s->cond), NULL);
    s->value = value;

    return;
}

void sem_wait(m_sem_t *s) {
    pthread_mutex_lock(&(s->mutex));
    while (s->value <= 0)
        pthread_cond_wait(&(s->cond), &(s->mutex));
    s->value--;
    pthread_mutex_unlock(&(s->mutex));

    return;
}

void sem_post(m_sem_t *s) {
    pthread_mutex_lock(&(s->mutex));
    s->value++;
    pthread_cond_broadcast(&(s->cond));
    pthread_mutex_unlock(&(s->mutex));

    return;
}
